package com.dc.chat.websocket.eventhandler;
import com.dc.chat.websocket.event.LogoutEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import javax.annotation.Resource;
import java.util.Map;

@Component
public class DisConnectionHandler implements ApplicationListener<SessionDisconnectEvent> {
    @Resource
    RedisTemplate redisTemplate;
    @Autowired
    ApplicationContext applicationContext;
    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        String admin = (String) ((Map) StompHeaderAccessor.wrap(event.getMessage()).toMap().get("simpSessionAttributes")).get("admin");
        if(admin==null){
            String username = (String) ((Map) StompHeaderAccessor.wrap(event.getMessage()).toMap().get("simpSessionAttributes")).get("username");
            String key = (String) ((Map) StompHeaderAccessor.wrap(event.getMessage()).toMap().get("simpSessionAttributes")).get("key");
            redisTemplate.delete(key);
            redisTemplate.opsForHash().delete("login",username);
            applicationContext.publishEvent(new LogoutEvent(this,username));
            System.out.println(username+"下线了");
        }else{
            redisTemplate.delete(admin);
            redisTemplate.opsForSet().remove("admin",admin);
        }
    }

}
